import nedb from '@/db/nedb'
import store from '../../store'
import { sendSock } from '../websocket'

/**
 * 新的朋友申请通知
 */
function friendAddReqeustNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  console.log('新的朋友申请：FriendAddReqeustNotice')
  console.log(msg)
  let userId = store.getters.userId
  message.user = userId
  message.ReqTime = new Date().getTime()
  console.log(message)
  // 新的朋友通知
  store.dispatch('friend/SetNewFriendNotice', true)

  // 好友申请插入数据库
  nedb.newFriends.update(
    { user: userId, WeChatId: message.WeChatId, FriendId: message.FriendId },
    { $set: message },
    { upsert: true },
    (err, numberReplace) => {
      console.log(err || numberReplace)
      store.dispatch('friend/SetNewFriendsList')
    }
  )

  //   nedb.newFriends.(message, (err, newDoc) => {
  //     console.log(err || newDoc)
  //     store.dispatch('friend/SetNewFriendsList')
  //   })
  // 自动通过是否开启 如果开启自动通过
  nedb.autoAcceptConfig.findOne({ user: userId }, (err, doc) => {
    console.log(err || doc)
    if (doc && doc.open) {
      console.log('自动通过好友请求 打开')
      console.log(doc.wechats)
      if (doc.wechats.indexOf(message.WeChatId) >= 0) {
        console.log('该微信可以自动通过')
        let autoAcceptMessage = {
          MsgType: 'AcceptFriendAddRequestTask',
          Content: {
            WeChatId: message.WeChatId,
            FriendId: message.FriendId,
            Operation: 1,
            Remark: doc.remark,
            FriendNick: ''
          }
        }
        console.log(autoAcceptMessage)
        sendSock(autoAcceptMessage)
      }
    } else if (doc && !doc.open) {
      console.log('自动通过好友请求关闭')
    }
  })
}

/**
 * 新的朋友列表
 * @param {*} msg
 */
function friendAddReqListNoticeHandle (msg) {
  let message = JSON.parse(msg.message)
  console.log('新的朋友列表:FriendAddReqListNotice')
  console.log(message)
  if (message.Requests) {
    let userId = store.getters.userId
    let wechatId = message.WeChatId
    let docs = []
    nedb.newFriends.remove(
      { user: userId, WeChatId: wechatId },
      { multi: true },
      (err, numberRemove) => {
        if (err) return
        console.log(numberRemove)
        for (const req of message.Requests) {
          req.user = userId
          req.WeChatId = wechatId
          docs.push(req)
        }
        nedb.newFriends.insert(docs, (err, newDocs) => {
          if (err) return
          store.dispatch('SetDialog', '')
          store.dispatch('friend/SetNewFriendsList')
        })
      }
    )
  } else {
    store.dispatch('SetDialog', '')
  }
}

export default {
  friendAddReqeustNoticeHandle,
  friendAddReqListNoticeHandle
}
